package com.it.shiro.config;

import com.it.shiro.pojo.UserBean;
import com.it.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;


/**
 * ClassName:MobileRelm
 * Package:com.it.shiro.config
 * Description: 描述信息
 * @date:2022/4/1 14:24
 * @author:动力节点
 */
@Configuration
public class MobileRealm extends AuthenticatingRealm {

    @Resource
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(MobileRealm.class);
    /**
     *
     * @param token
     * @return 获取身份验证信息
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info(">>>entered MobileRealm doGetAuthenticationInfo method");
        //获取当前用户
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //获得数据库中的用户，来跟当前地用户进行比对，认证。
        String userMobile = userToken.getUsername();
        //当前用户和数据库中的用户进行密码匹配
        UserBean userBean = userService.queryUserByMobile(userMobile);
        //如果没有查到,表示没有这个用户
        if (userBean == null){
            return null; //会抛出UnknownAccountException异常
        }
        // 3、当前用户和数据库中的用户进行密码设置，shiro自带密码比对
        ByteSource salt = ByteSource.Util.bytes("salt");
        //返回AuthenticationInfo，完成了认证流程
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userBean,userBean.getUserPass(),salt,"MyRealm");
        return simpleAuthenticationInfo;
    }
}

